package com.qf.controller;

import com.qf.config.RedisLockUtil;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author 汤奇
 * @version V1.0
 * @Project BookPro
 * @Package com.qf.controller
 * @Description: 模拟高并发秒杀下单
 * @Date 2022/7/11 19:30
 */
@RestController
public class SeckillController {

    //1.准备商品库存
    public static Map<String,Integer> itemStock = new HashMap<>();

    //2.准备商品订单
    public static Map<String,Integer> itemOrder= new HashMap<>();

    @Autowired
    private CuratorFramework cf;

    @Autowired
    private RedisLockUtil redisLockUtil;

    static {
        //初始化库存数据
        itemStock.put("詹野种",10000);

        //初始化订单数据
        itemOrder.put("詹野种",0);
    }

    /**
     * 模拟下单秒杀
     * @param item 商品名称
     * @return
     * @throws Exception
     */
    @RequestMapping("/kill")
    public String kill(String item) throws  Exception{

        //============创建zookeeper锁对象================
//        InterProcessMutex lock = new InterProcessMutex(cf, "/lock");

        //============zookeeper加锁================
        //if (lock.acquire(1, TimeUnit.SECONDS)) {
        //============zookeeper加锁================

        //============Redis加锁================
        if (redisLockUtil.lock(item, String.valueOf(System.currentTimeMillis()),1)){
        //============Redis加锁================
            //1.减库存
            Integer stock = itemStock.get(item);
            if (stock <= 0) {
                return "库存不足!!!";
            }

            //扣库存
            itemStock.put(item, stock - 1);

            //2.创建订单
            itemOrder.put(item, itemOrder.get(item) + 1);

            //============zookeeper解锁================
            //lock.release();
            //============zookeeper解锁================

            //============Redis解锁================
            redisLockUtil.unlock(item);
            //============Redis解锁================

            //3.返回下单提示信息
            return "抢购成功, " + item + "库存:" + itemStock.get(item) + ", 订单:" + itemOrder.get(item);
        } else {
            return "没抢到商品";
        }
    }
}
